<template>
  <div class="page">
    <h2>个体与团体干预</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按姓名/工号/内容搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="filterMode" placeholder="全部模式" style="width:160px">
        <el-option label="全部模式" :value="''" />
        <el-option label="个体" value="individual" />
        <el-option label="团体" value="group" />
      </el-select>

      <el-select v-model="filterStatus" placeholder="随访状态" style="width:140px">
        <el-option label="全部" :value="''" />
        <el-option label="未随访" value="pending" />
        <el-option label="已随访" value="done" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新增记录</el-button>
        <el-button @click="exportCSV">导出记录</el-button>
      </div>
    </div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="person" label="工号/姓名" width="180" />
      <el-table-column prop="mode" label="模式" width="120">
        <template #default="{ row }">{{ row.mode==='group' ? '团体' : '个体' }}</template>
      </el-table-column>
      <el-table-column prop="therapist" label="干预人员" width="140" />
      <el-table-column prop="date" label="日期" width="160" />
      <el-table-column prop="status" label="随访" width="100">
        <template #default="{ row }"><el-tag :type="row.status==='done' ? 'success' : 'info'">{{ row.status==='done' ? '已随访' : '未随访' }}</el-tag></template>
      </el-table-column>
      <el-table-column prop="summary" label="干预摘要" />
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" @click="view(row.id)">查看</el-button>
          <el-button size="small" @click="openModal(row.id)" style="margin-left:8px">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteOne(row.id)" style="margin-left:8px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button @click="batchSetStatus('done')">标记已随访</el-button>
      <el-button @click="batchSetStatus('pending')">标记未随访</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <el-dialog :title="editingId ? '编辑记录' : '新增记录'" v-model="showModal" width="720px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="工号/姓名">
          <el-input v-model="form.person" placeholder="F001 - 张三" />
        </el-form-item>
        <el-form-item label="模式">
          <el-select v-model="form.mode" style="width:180px">
            <el-option label="个体" value="individual" />
            <el-option label="团体" value="group" />
          </el-select>
        </el-form-item>
        <el-form-item label="干预人员">
          <el-input v-model="form.therapist" />
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker v-model="form.date" type="datetime" placeholder="选择时间" style="width:220px" />
        </el-form-item>
        <el-form-item label="干预摘要">
          <el-input type="textarea" v-model="form.summary" />
        </el-form-item>
        <el-form-item label="随访计划/建议">
          <el-input type="textarea" v-model="form.followup" />
        </el-form-item>
        <el-form-item label="随访状态">
          <el-select v-model="form.status" style="width:160px">
            <el-option label="未随访" value="pending" />
            <el-option label="已随访" value="done" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const DEFAULT_DATA = [
  { id:1, person:'F001 - 张强', mode:'individual', therapist:'王医生', date:'2025-09-15 10:00', status:'done', summary:'短程认知行为干预，情绪稳定', followup:'2周随访' },
  { id:2, person:'F003 - 王伟', mode:'group', therapist:'李心理师', date:'2025-09-20 14:00', status:'pending', summary:'团体减压训练（8人）', followup:'每月一次' }
];

const data = ref([]);
const q = ref('');
const filterMode = ref('');
const filterStatus = ref('');
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ person:'', mode:'individual', therapist:'', date:'', summary:'', followup:'', status:'pending' });

onMounted(()=>{ load(); });
function load(){ data.value = JSON.parse(JSON.stringify(DEFAULT_DATA)); }

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(d.person.toLowerCase().includes(qq) || (d.summary||'').toLowerCase().includes(qq))) return false;
    if(filterMode.value && d.mode !== filterMode.value) return false;
    if(filterStatus.value && d.status !== filterStatus.value) return false;
    return true;
  });
});

watch(selectedRows, v=>{ selectedIds.value = v.map(i=>i.id); });
function onSelectionChange(rows){ selectedRows.value = rows; }

function openModal(id){ editingId.value = id || null; if(id){ const it = data.value.find(x=>x.id===id); if(it) Object.assign(form, JSON.parse(JSON.stringify(it))); } else{ Object.assign(form,{person:'',mode:'individual',therapist:'',date:'',summary:'',followup:'',status:'pending'}); } showModal.value = true; }
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.person){ ElMessage.warning('工号/姓名为必填项'); return; } if(editingId.value){ const it = data.value.find(x=>x.id===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); } else{ const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push(Object.assign({ id:nid }, JSON.parse(JSON.stringify(form)))); } showModal.value=false; ElMessage.success('保存成功'); }

function view(id){ const it = data.value.find(x=>x.id===id); if(it){ ElMessage.info(`${it.person} ${it.mode==='group'?'团体':'个体'} ${it.date}`); } }

function deleteOne(id){ ElMessageBox.confirm('确认删除该记录？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(x=>x.id!==id); ElMessage.success('已删除'); })
  .catch(()=>{});
}
function batchSetStatus(s){ const ids = selectedIds.value.slice(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } data.value.forEach(d=>{ if(ids.includes(d.id)) d.status = s; }); ElMessage.success('操作完成'); }
function batchDelete(){ const ids = selectedIds.value.slice(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条记录？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.id)); selectedIds.value = []; selectedRows.value = []; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){ const csv = [ ['id','person','mode','therapist','date','status','summary','followup'], ...data.value.map(d=>[d.id,d.person,d.mode,d.therapist,d.date,d.status,d.summary||'',d.followup||'']) ]; const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n'); const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='firefighter_interventions.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }

function onClear(){ }
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>